package com.github.postsanf.yinian.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.HongbaoChartAdapter;
import com.github.postsanf.yinian.bean.YNHongBaoChart;
import com.github.postsanf.yinian.bean.YNReceiverInfo;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YnRedEnvelopInfo;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.utils.BigDecimalUtil;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class PaiLidePaiHangActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView rv_members;
    private HongbaoChartAdapter mAdapter;
    private List<YNHongBaoChart> mMemberDatas = new ArrayList<>();
    private SimpleDraweeView paihang_avatar;
    private TextView hongbaopaihang_name;
    private TextView hongbaopaihang_mymoney;
    private LinearLayout money_show;
    private ImageView money_over;
    private TextView hongbaopaihang_detail;
    private RecyclerViewHeader headview;
    private YNStatus ynStatus;
    private YnRedEnvelopInfo ynRedEnvelopInfo;
    boolean redover = false;
    boolean fromRedOpen = false;
    private YNReceiverInfo ynReceiverInfo;
    private String grabMoney;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pailide_paihang);
        ynStatus = YNSingleton.getInstance().getCurStatus();
        ynRedEnvelopInfo = ynStatus.getRedEnvelopInfo();
        if (getIntent() != null) {
            redover = getIntent().getBooleanExtra("redover", false);
            fromRedOpen = getIntent().getBooleanExtra("fromRedOpen", false);
            if (fromRedOpen) {
                ynReceiverInfo = (YNReceiverInfo) getIntent().getSerializableExtra("ynReceiverInfo");
                grabMoney = ynReceiverInfo.getGrabMoney();
            }
        }
        initView();
        noticePaihangServiceInit();
        headview = RecyclerViewHeader.fromXml(this, R.layout.activity_hongbaopaihang_top);
        paihang_avatar = (SimpleDraweeView) headview.findViewById(R.id.hongbaopaihang_avatar);
        hongbaopaihang_name = (TextView) headview.findViewById(R.id.hongbaopaihang_name);
        hongbaopaihang_mymoney = (TextView) headview.findViewById(R.id.hongbaopaihang_mymoney);
        money_show = (LinearLayout) headview.findViewById(R.id.money_show);
        money_over = (ImageView) headview.findViewById(R.id.money_over);
        hongbaopaihang_detail = (TextView) headview.findViewById(R.id.hongbaopaihang_detail);
        ImageOptHelper.showFrescoBlur(Uri.parse(ynStatus.getPublishUser().getUpic()), paihang_avatar, PaiLidePaiHangActivity.this);
        hongbaopaihang_name.setText(ynStatus.getPublishUser().getUnickname() + "的红包");
        if (fromRedOpen) {
            hongbaopaihang_detail.setText("已领取了" + (ynRedEnvelopInfo.getRedEnvelopTotalNum() - (ynRedEnvelopInfo.getRedEnvelopRemainNum()) + 1) + "/" + ynRedEnvelopInfo.getRedEnvelopTotalNum() + "个，共有" +
                    BigDecimalUtil.add(BigDecimalUtil.sub(ynRedEnvelopInfo.getRedEnvelopTotalMoney(), ynRedEnvelopInfo.getRedEnvelopRemainMoney()), grabMoney) + "/" + ynRedEnvelopInfo.getRedEnvelopTotalMoney() + "元");
        } else {
            hongbaopaihang_detail.setText("已领取了" + (ynRedEnvelopInfo.getRedEnvelopTotalNum() - ynRedEnvelopInfo.getRedEnvelopRemainNum()) + "/" + ynRedEnvelopInfo.getRedEnvelopTotalNum() + "个，共有" +
                    BigDecimalUtil.sub(ynRedEnvelopInfo.getRedEnvelopTotalMoney(), ynRedEnvelopInfo.getRedEnvelopRemainMoney()) + "/" + ynRedEnvelopInfo.getRedEnvelopTotalMoney() + "元");
        }
        if (redover) {
            money_over.setVisibility(View.VISIBLE);
            money_show.setVisibility(View.GONE);
        } else {
            money_over.setVisibility(View.GONE);
            money_show.setVisibility(View.VISIBLE);
        }
        headview.attachTo(rv_members);
    }

    private void initView() {
        findViewById(R.id.top_back).setOnClickListener(this);
        rv_members = (RecyclerView) findViewById(R.id.rv_members);
        rv_members.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new HongbaoChartAdapter(this, mMemberDatas);
        rv_members.setAdapter(mAdapter);
        rv_members.setHasFixedSize(true);
    }


    private void noticePaihangServiceInit() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        if (redover) {
            mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(ynStatus.getReceiveInfo().get(0).getUserid()));
        } else {
            mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        }
        mParam.put(CommonConstants.YNS_REDENVELOPID, String.valueOf(ynRedEnvelopInfo.getRedEnvelopID()));
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/user/ShowRedEnvelopInfo")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "paihang===>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optInt("code") == 0) {
                                JSONArray totalarray = jsonObject.optJSONArray("data").optJSONObject(0).optJSONArray("grabList");
                                for (int i = 0; i < totalarray.length(); i++) {
                                    if (Integer.parseInt(totalarray.optJSONObject(i).optString("userid")) == application.getCurID()) {
                                        hongbaopaihang_mymoney.setText(totalarray.optJSONObject(i).optString("grabMoney"));
                                    }
                                    YNHongBaoChart ynChart = new YNHongBaoChart();
                                    ynChart.setUpic(totalarray.optJSONObject(i).optString("upic"));
                                    ynChart.setGrabMoney(totalarray.optJSONObject(i).optString("grabMoney"));
                                    ynChart.setGrabTime(totalarray.optJSONObject(i).optString("grabTime"));
                                    ynChart.setUserid(totalarray.optJSONObject(i).optString("userid"));
                                    ynChart.setUnickname(totalarray.optJSONObject(i).optString("unickname"));
                                    mMemberDatas.add(ynChart);
                                }
                                mAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    @Override
    public void onBackPressed() {
        updateshow();
        finish();
    }

    void updateshow() {
        if (fromRedOpen) {
            ynStatus.getReceiveInfo().add(ynReceiverInfo);
            YnRedEnvelopInfo ynRedEnvelopInfo = new YnRedEnvelopInfo();
            ynRedEnvelopInfo.setRedEnvelopTotalNum(ynStatus.getRedEnvelopInfo().getRedEnvelopTotalNum());
            ynRedEnvelopInfo.setRedEnvelopRemainNum(ynStatus.getRedEnvelopInfo().getRedEnvelopRemainNum() - 1);
            ynRedEnvelopInfo.setRedEnvelopRemainMoney(BigDecimalUtil.sub(ynStatus.getRedEnvelopInfo().getRedEnvelopRemainMoney(), ynReceiverInfo.getGrabMoney()));
            ynRedEnvelopInfo.setRedEnvelopTotalMoney(ynStatus.getRedEnvelopInfo().getRedEnvelopTotalMoney());
            ynRedEnvelopInfo.setRedEnvelopID(ynStatus.getRedEnvelopInfo().getRedEnvelopID());
            ynStatus.setRedEnvelopInfo(ynRedEnvelopInfo);
            Intent ynStatusintent = new Intent(ACTIONs.actionReceiveInfo);
            ynStatusintent.putExtra("ynstatus", ynStatus);
            sendBroadcast(ynStatusintent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_back:
                updateshow();
//                sendBroadcast(new Intent(ACTIONs.actionCloseactivity));
                finish();
                break;
        }
    }
}
